package com.ciwong.epaper.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.libs.utils.DeviceUtils;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

/**
 * 顶部轮播
 *
 * @author Administrator
 */
public class MyTopParouselViewPager extends ViewPager {
    // 图片的连接地址
    private List<String> imgUrls;

    // 点击监听
    private OnTopParouselListener listener;

    // ViewPager的适配器
    private MyPagerAdapter myPagerAdapter;

    // 第一次设定Item的位置
    private boolean isFirst = true;

    // 点的集合
    private List<View> points;

    // 按下ViewPager时的坐标
    private float downX;

    private TextView top_news_title;

    private List<String> titleList;

    private Context context;

    private int position = 0;

    private Rect mRect;
    private int[] location = new int[2];

    public MyTopParouselViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public MyTopParouselViewPager(Context context) {
        this(context, null);
    }

    private LinearLayout.LayoutParams layoutParams;

    private LinearLayout.LayoutParams layoutParams1;

    @SuppressWarnings("deprecation")
    private void init() {

        this.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
//                CWLog.d("MyTopParouselViewPager", "onPageSelected()" + position);
                if (top_news_title != null) {
                    top_news_title.setText((position % imgUrls.size()) + 1 + "/"
                            + imgUrls.size());
                }

                if (imgUrls != null) {
                    MyTopParouselViewPager.this.position = position
                            % imgUrls.size();
                    position = position % imgUrls.size();
                    // 轮播
                    if (listener != null && isVISIBLE()) {
                        listener.onShuffling(position);

                    }
                    // 设置选中图片的配套文字
                    // top_news_title.setText(titleList.get(position));
                    // 设置选中的点
                    if (points != null && points.size() > 1) {
                        for (int j = 0; j < points.size(); j++) {
                            if (j == position) {
                                points.get(j).setBackgroundResource(
                                        R.mipmap.dot_focus);
                                if (layoutParams == null) {
                                    // 设置view对象宽高的操作
                                    int width = 16; // PhoneUtils.dip2px(context,
                                    // 8);
                                    // 设置view对象间的间距
                                    int margin = 6; // PhoneUtils.dip2px(context,
                                    // 3);
                                    // 设置view对象宽高的操作
                                    layoutParams = new LinearLayout.LayoutParams(
                                            (int) (width * 1.5), width);
                                    // 设置view对象间的间距
                                    layoutParams.setMargins(margin, 0, margin,
                                            0);
                                }
                                points.get(j).setLayoutParams(layoutParams);
                            } else {
                                points.get(j).setBackgroundResource(
                                        R.mipmap.dot_normal);

                                if (layoutParams1 == null) {
                                    // 设置view对象宽高的操作
                                    int width = 16; // PhoneUtils.dip2px(context,
                                    // 8);
                                    // 设置view对象间的间距
                                    int margin = 6; // PhoneUtils.dip2px(context,
                                    // 3);
                                    // 设置view对象宽高的操作
                                    layoutParams1 = new LinearLayout.LayoutParams(
                                            width, width);
                                    // 设置view对象间的间距
                                    layoutParams1.setMargins(margin, 0, margin,
                                            0);
                                }

                                points.get(j).setLayoutParams(layoutParams1);
                            }
                        }
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        mRect = new Rect(0, 0, DeviceUtils.getScreenWdith(), DeviceUtils.getScreenWdith());
        this.getLocationInWindow(location);
    }

    private class MyPagerAdapter extends PagerAdapter {
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // ImageView iv = new ImageView(getContext());
            SimpleDraweeView mSimpleDraweeView = new SimpleDraweeView(
                    getContext());

            mSimpleDraweeView.getHierarchy()
                    .setActualImageScaleType(ScalingUtils.ScaleType.FIT_XY);

            RoundingParams roundingParams = RoundingParams.fromCornersRadius(10f);
            mSimpleDraweeView.getHierarchy().setRoundingParams(roundingParams);
            // iv.setScaleType(ScaleType.CENTER_CROP);
            // 网络加载图片
            if (imgUrls != null) {
                position = position % imgUrls.size();
                // 设置图片
                // mSimpleDraweeView.setImageURI(Uri.parse(imgUrls.get(position)));
                setImageURI(mSimpleDraweeView, imgUrls.get(position));
            }
            container.addView(mSimpleDraweeView);
            return mSimpleDraweeView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            if (imgUrls == null || imgUrls.size() == 0) {
                return 1;
            }
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
    }

    /**
     * 开始轮播
     */
    public void startRoll() {
        if (imgUrls != null && imgUrls.size() > 0) {
            if (myPagerAdapter == null) {
                myPagerAdapter = new MyPagerAdapter();
                setAdapter(myPagerAdapter);
            } else {
                myPagerAdapter.notifyDataSetChanged();
            }
            if (isFirst) {
                setCurrentItem(1000 - (1000 % imgUrls.size())
                        + MyTopParouselViewPager.this.getCurrentItem()
                        % imgUrls.size());
                isFirst = false;
            }
            roll();
        }
    }

    /**
     * 滚动
     */
    public void roll() {
        clearRoll();
        if (imgUrls.size() > 1) {
            handler.sendEmptyMessage(0);
        }
    }

    /**
     * 清空轮播
     */
    public void clearRoll() {
        handler.removeCallbacksAndMessages(null);
    }

    RunnableTask runnableTask = new RunnableTask();

    class RunnableTask implements Runnable {
        @Override
        public void run() {
            // 维护一个计算规则，0,1,2,3,0,1,2,3
            MyTopParouselViewPager.this.setCurrentItem(
                    MyTopParouselViewPager.this.getCurrentItem() + 1);
            // 发送一个消息，给handlerMessage方法处理
            handler.obtainMessage().sendToTarget();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // 改变当前的页面选项
            handler.postDelayed(runnableTask, 6000);
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = ev.getX();
                clearRoll();
                break;
            case MotionEvent.ACTION_CANCEL:
                roll();
                break;
            case MotionEvent.ACTION_UP:
                roll();
                float upX = ev.getX();
                if (Math.abs(upX - downX) < 10) {
                    // 点击代码
                    if (listener != null) {
                        // TODO useNotice(actUrls.get(position));
                        listener.onClick(position);
                    }
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    private int downX1;

    private int downY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 夫控件不可以去拦截事件
                getParent().requestDisallowInterceptTouchEvent(true);
                downX1 = (int) ev.getX();
                downY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();

                if (Math.abs(moveX - downX1) < Math.abs(moveY - downY)) {
                    // y轴上面移动的多，刷新操作，需要去拦截事件
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    // x轴上面的移动距离比Y上的多
                    // 由左边向右边移动 moveX-downX>0
                    // 由右边向左边移动 moveX-downX<0
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }


    /**
     * 移除所有的消息
     */
    protected void onDetachedFromWindow() {
        clearRoll();
        super.onDetachedFromWindow();
    }

    /**
     * 设置图片集合
     *
     * @param imgList
     */
    public void setImgList(List<String> imgList) {
        this.imgUrls = imgList;
    }

    /**
     * 设置点的集合
     *
     * @param points
     */
    public void setPoints(List<View> points) {
        this.points = points;
    }

    /**
     * 设置点击
     *
     * @param listener
     */
    public void setOnClickListener(OnTopParouselListener listener) {
        this.listener = listener;
    }

    // 初始化文字的操作
    public void initTitle(List<String> titleList, TextView top_news_title) {
        if (null != titleList && null != top_news_title && titleList.size() > 0) {
            top_news_title.setText(titleList.get(0));
        }
        this.top_news_title = top_news_title;
        this.titleList = titleList;
    }

    /**
     * 设置图片张数
     *
     * @param top_news_title
     */
    public void setTitle(TextView top_news_title) {
        this.top_news_title = top_news_title;
    }

    /**
     * 点击监听
     */
    public interface OnTopParouselListener {

        /**
         * 点击
         *
         * @param position
         */
        void onClick(int position);

        /**
         * 轮播
         *
         * @param position
         */
        void onShuffling(int position);
    }

    /**
     * 获取当前轮播的位置
     *
     * @return
     */
    public int getCurrentPosition() {
        this.getVisibility();
        return position;
    }

    public boolean isVISIBLE() {

        if (this.getLocalVisibleRect(mRect)) {
            return true;
        }
        return false;
    }

    /**
     * 设置图片(原图)
     *
     * @param imageView 显示图片控件
     * @param url       图片地址
     */
    public static void setImageURI(SimpleDraweeView imageView, String url) {
        if (!TextUtils.isEmpty(url)) {
            Uri uri = Uri.parse(url);
            setImageURI(imageView, uri);
        } else {
            imageView.setImageResource(-1);
        }
    }

    /**
     * 设置图片最终方法
     *
     * @param imageView 显示图片控件
     * @param uri       图片URI
     */
    public static void setImageURI(SimpleDraweeView imageView, Uri uri) {
        if (imageView != null && uri != null) {
            imageView.setImageURI(uri);
        }
    }
}
